<?php

namespace app\common\model;

use think\Model;
use think\Config;
use think\Log;

/**
 * 微信客服接口操作类
 */
class TemplateMessageModel extends Model
{
    protected $name = '';
	
	//公众号主动发自定义模板消息
	public function user_custom_tplmsg($target_id, $form_id,$keyword1, $keyword2='',$keyword3='', $url = '', $template_id = ''){

        $param['data']['keyword1']['value'] = $keyword1;
        $param['data']['keyword1']['color'] = "#E60B43";
		if(!empty($keyword2)){
			$param['data']['keyword2']['value'] = $keyword2;
			$param['data']['keyword2']['color'] = "#173177";
		}
		if(!empty($keyword3)){
			$param['data']['keyword3']['value'] = $keyword3;
			$param['data']['keyword3']['color'] = "#173177";
		}
        $param['data']['emphasis_keyword'] = "keyword1.DATA";//模板需要放大的关键词

        $template_id == '' && $template_id = $tpl_data['tpl_id'];//lyGkjyjZhYyMg8pr7F1vyQfa48owZ4KyEUGWoQinUJc

        return $this->_replyData($target_id,$form_id, $param, $template_id, $url);
    }

    /* 发送回复模板消息到微信平台 */
    function _replyData($target_id,$form_id, $param, $template_id, $jumpUrl = ''){
		if(!is_numeric($target_id)){//openid
			$ret['openid'] = $target_id;
		}else{//uid
			$map ['uid'] = $target_id;
			$ret = db('user')->where($map)->find();
		}
        if ($ret) {
            $param ['touser'] = $ret['openid'];
            $param['template_id'] = $template_id;
            $param['form_id'] = $form_id;
            $param['page'] = $jumpUrl;//
            $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . get_wxapp_access_token();
            // die;
            $res = post_data($url, $param);
			//var_dump($param);exit;
            Log::record("\r\n"."url:api/TemplateMsg/send \r\n".'url:'.$url." \r\n params:".json_encode($param)." \r\n result:".json_encode($res),'send_message_log');
            if ($res ['errcode'] != 0) {
                $result ['status'] = 0;
                $result ['msg'] = $res['errmsg'];
            } else {
                $result ['status'] = 1;
                $result ['msg'] = '发送成功';
            }
        } else {
            $result ['status'] = 0;
            $result ['msg'] = '发送失败'.$result ['errmsg'];
        }
        return $result;
    }
	
}

?>
